<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon
        :closable="false">
      </el-alert>
      <!-- 商品分类区域 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框 -->
          <el-cascader v-model="selectedCateKeys" :options="cateList"
            :props="cateProps" @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeTabName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini"
            :disabled="isBtnDisable" @click="addDialogVisible = true">
            添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 属性参数展示的标签 -->
              <template v-slot="scope">
                <el-tag v-for=" (item,i) in scope.row.attr_vals"
                  :key="i" closable
                  @close="handleTagClose(i,scope.row)">{{item}}
                </el-tag>
                <!-- 输入的文本输入框 -->
                <el-input class="input-new-tag"
                  v-if="scope.row.inputTagVisible"
                  v-model="scope.row.inputTagValue" ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputTagConfirm(scope.row)"
                  @blur="handleInputTagConfirm(scope.row)">
                </el-input>
                <!-- 添加tag按钮 -->
                <el-button v-else class="button-new-tag" size="small"
                  @click="showInput(scope.row)">+ 添加标签</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete"
                  size="mini" @click="removeParam(scope.row.attr_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini"
            :disabled="isBtnDisable" @click="addDialogVisible = true">
            添加属性
          </el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 静态属性参数展示的标签 -->
              <template v-slot="scope">
                <el-tag v-for=" (item,i) in scope.row.attr_vals"
                  :key="i" closable
                  @close="handleTagClose(i,scope.row)">{{item}}
                </el-tag>
                <!-- 输入的文本输入框 -->
                <el-input class="input-new-tag"
                  v-if="scope.row.inputTagVisible"
                  v-model="scope.row.inputTagValue" ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputTagConfirm(scope.row)"
                  @blur="handleInputTagConfirm(scope.row)">
                </el-input>
                <!-- 添加tag按钮 -->
                <el-button v-else class="button-new-tag" size="small"
                  @click="showInput(scope.row)">+ 添加标签</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete"
                  size="mini" @click="removeParam(scope.row.attr_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加'+titleText"
      :visible.sync="addDialogVisible" width="50%"
      @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef"
        label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消
        </el-button>
        <el-button type="primary" @click="addParams">确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改'+titleText"
      :visible.sync="editDialogVisible" width="50%"
      @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules"
        ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消
        </el-button>
        <el-button type="primary" @click="editParams">确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 商品分类数据
      cateList: [],
      //   级联选择框配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      //   级联选择框双向绑定到的数组
      selectedCateKeys: [],
      //   被激活的页签名称
      activeTabName: 'many',
      //   动态参数数据
      manyTabData: [],
      //   静态属性数据
      onlyTabData: [],
      //   控制添加对话框的展示
      addDialogVisible: false,
      //   添加表单的数据对象
      addForm: {
        attr_name: ''
      },
      //   添加表单的验证规则
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '参数名称的长度在2到10个字符之间',
            trigger: 'blur'
          }
        ]
      },
      //   控制修改对话框的显示与否
      editDialogVisible: false,
      // 修改的表单数据对象
      editForm: {},
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '参数名称的长度在2到10个字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    isBtnDisable() {
      // 按钮是否需要被禁用
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中三级分类id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 动态计算标题文本
    titleText() {
      if (this.activeTabName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  methods: {
    //   获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败！')
      }
      this.cateList = res.data
    },
    // 级联选择框变化时触发
    handleChange() {
      this.getParamsData()
    },
    // 获取参数的列表数据
    async getParamsData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTabData = []
        this.onlyTabData = []
        return
      }
      //   根据所选分类的id和当前所处面板获取对应参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeTabName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败！')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 标签是否显示输入框
        item.inputTagVisible = false
        // 标签内输入框内容
        item.inputTagValue = ''
      })
      if (this.activeTabName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    // tab页签点击事件处理函数
    handleTabClick() {
      this.getParamsData()
    },
    // 监听添加对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮添加参数
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeTabName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品分类列表失败！')
        }
        this.$message.success('添加商品分类列表成功！')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 点击按钮展示修改参数对话框
    async showEditDialog(attr_id) {
      // 查询当前参数信息
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeTabName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('查询当前参数信息列表失败！')
      }

      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改对话框的关闭事件
    editDialogClosed() {
      // categories/:id/attributes/:attrId
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮修改参数
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeTabName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改商品参数失败！')
        }
        this.$message.success('修改商品参数成功！')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // categories/:id/attributes/:attrid
    // 根据id删除参数属性
    async removeParam(attr_id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除商品参数失败！')
      }
      this.getParamsData()
      this.$message.success('删除商品参数成功！')
    },
    // 文本框失去焦点或者enter触发添加事件
    handleInputTagConfirm(row) {
      const str = '添加'
      if (row.inputTagValue.trim().length === 0) {
        row.inputTagValue = ''
        row.inputTagVisible = false
        return
      }
      row.attr_vals.push(row.inputTagValue.trim())
      row.inputTagValue = ''
      row.inputTagVisible = false
      this.saveAttr_vals(row, str)
    },
    // 点击按钮展示文本输入框
    showInput(row) {
      row.inputTagVisible = true
      // $nextTick的作用是元素被重新渲染之后才会执行回调函数中的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除对应的标签
    handleTagClose(index, row) {
      const str = '删除'
      row.attr_vals.splice(index, 1)
      this.saveAttr_vals(row, str)
    },
    async saveAttr_vals(row, str) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(str + '参数标签失败！')
      }
      this.$message.success(str + '参数标签成功！')
    }
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 90px;
}
</style>